﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using System.Configuration;
using System.IO;

namespace PetroMentor.Service
{
    public sealed class NHibernateHelper
    {
        private readonly string path = System.AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["hibernatecfg"].ToString();
        private readonly string logpath = System.AppDomain.CurrentDomain.BaseDirectory + "log4net.cfg.xml";
        

        private static ISessionFactory _sessionFactory;
        private static NHibernateHelper _instance;
        public static NHibernateHelper Instance()
        {
            if (_instance != null)
                return _instance;
            else
            {
                _instance = new NHibernateHelper();
                return _instance;
            }
        }
        private NHibernateHelper()
        {
            _sessionFactory = GetSessionFactory();
            log4net.Config.XmlConfigurator.Configure(new FileInfo(logpath));
            
        }
        
        private ISessionFactory GetSessionFactory()
        {
            if (_sessionFactory != null)
                return _sessionFactory;
            else
            {
                try
                {
                    _sessionFactory = (new NHibernate.Cfg.Configuration()).Configure(path).BuildSessionFactory();
                    return _sessionFactory;
                }
                catch(Exception ex)
                {
                    return null;
                }

               
                
            }
        }
        public ISession GetSession()
        {
            return _sessionFactory.OpenSession();
        }
    }
}